<template>
  <div class="running-app bg-gray-100 min-h-screen text-gray-800 font-sans">
    <!-- 顶部导航栏 -->
    <header class="bg-green-600 text-white p-4 flex items-center justify-between shadow-md">
      <div class="flex items-center">
        <div class="w-10 h-10 bg-white rounded-full flex items-center justify-center mr-3">
          <span class="text-green-600 font-bold text-lg">大</span>
        </div>
        <h1 class="text-xl font-bold">跃动西大</h1>
      </div>
      <div class="flex items-center">
        <span class="mr-2">{{ studentInfo.name }}</span>
        <div class="w-8 h-8 bg-white rounded-full overflow-hidden">
          <img :src="studentInfo.avatar" alt="头像" class="w-full h-full object-cover" />
        </div>
      </div>
    </header>

    <!-- 打卡状态 -->
    <div class="bg-white mx-4 mt-4 rounded-lg shadow-md overflow-hidden">
      <div class="p-4 bg-green-50 border-b border-green-100">
        <h2 class="text-lg font-bold text-green-700">今日打卡</h2>
      </div>
      <div class="p-4">
        <div class="flex justify-between items-center mb-4">
          <div class="text-gray-600">{{ currentDate }}</div>
          <div :class="['px-3 py-1 rounded-full text-sm font-medium', isCheckedIn ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800']">
            {{ isCheckedIn ? '已打卡' : '未打卡' }}
          </div>
        </div>
        <button 
          @click="checkIn" 
          :disabled="isCheckedIn"
          :class="['w-full py-3 rounded-lg font-bold text-white transition-all', 
                  isCheckedIn ? 'bg-gray-400' : 'bg-green-600 active:bg-green-700']">
          {{ isCheckedIn ? '今日已完成打卡' : '立即打卡' }}
        </button>
      </div>
    </div>

    <!-- 跑步数据 -->
    <div class="grid grid-cols-3 gap-4 mx-4 mt-4">
      <div class="bg-white p-4 rounded-lg shadow-md flex flex-col items-center">
        <div class="text-3xl font-bold text-green-600 mb-1">{{ runningData.totalDays }}</div>
        <div class="text-sm text-gray-500">累计打卡</div>
      </div>
      <div class="bg-white p-4 rounded-lg shadow-md flex flex-col items-center">
        <div class="text-3xl font-bold text-green-600 mb-1">{{ runningData.totalDistance }}km</div>
        <div class="text-sm text-gray-500">累计里程</div>
      </div>
      <div class="bg-white p-4 rounded-lg shadow-md flex flex-col items-center">
        <div class="text-3xl font-bold text-green-600 mb-1">{{ runningData.points }}</div>
        <div class="text-sm text-gray-500">积分</div>
      </div>
    </div>

    <!-- 排行榜 -->
    <div class="bg-white mx-4 mt-4 rounded-lg shadow-md overflow-hidden">
      <div class="p-4 bg-green-50 border-b border-green-100 flex justify-between items-center">
        <h2 class="text-lg font-bold text-green-700">校园排行榜</h2>
        <span class="text-sm text-green-600">查看更多</span>
      </div>
      <div class="p-4">
        <div v-for="(user, index) in leaderboard" :key="index" 
             class="flex items-center py-3 border-b border-gray-100 last:border-0">
          <div :class="['w-6 h-6 rounded-full flex items-center justify-center mr-3 text-white font-medium', 
                       index === 0 ? 'bg-yellow-500' : 
                       index === 1 ? 'bg-gray-400' : 
                       index === 2 ? 'bg-amber-600' : 'bg-gray-300']">
            {{ index + 1 }}
          </div>
          <div class="w-8 h-8 rounded-full overflow-hidden mr-3">
            <img :src="user.avatar" alt="头像" class="w-full h-full object-cover" />
          </div>
          <div class="flex-1">
            <div class="flex items-center">
              <span class="font-medium">{{ user.name }}</span>
              <span class="ml-2 text-xs bg-blue-100 text-blue-800 px-2 py-0.5 rounded">{{ user.department }}</span>
            </div>
            <div class="text-xs text-gray-500">累计 {{ user.distance }}km</div>
          </div>
          <div class="text-green-600 font-bold">{{ user.points }}分</div>
        </div>
      </div>
    </div>

    <!-- 底部导航 -->
    <div class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 flex justify-around py-2">
      <div class="flex flex-col items-center text-green-600">
        <div class="i-carbon-home text-2xl"></div>
        <span class="text-xs mt-1">首页</span>
      </div>
      <div class="flex flex-col items-center text-gray-400">
        <div class="i-carbon-map text-2xl"></div>
        <span class="text-xs mt-1">跑步</span>
      </div>
      <div class="flex flex-col items-center text-gray-400">
        <div class="i-carbon-trophy text-2xl"></div>
        <span class="text-xs mt-1">排行</span>
      </div>
      <div class="flex flex-col items-center text-gray-400">
        <div class="i-carbon-user-profile text-2xl"></div>
        <span class="text-xs mt-1">我的</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getRunningLeaderboard, getUserRunningStats, checkTodayRunRecord, createRunRecord } from '@/api/run';
import { useUserStore } from '@/store/modules/user';

// 获取用户store
const userStore = useUserStore();

// 学生信息
const studentInfo = ref({
  id: userStore.studentInfo.id || '',
  name: userStore.studentInfo.name || '同学',
  avatar: userStore.studentInfo.avatar || 'https://randomuser.me/api/portraits/men/1.jpg',
  department: userStore.studentInfo.department || '计算机科学学院'
});

// 跑步数据
const runningData = ref({
  totalDays: 0,
  totalDistance: 0,
  points: 0
});

// 打卡状态
const isCheckedIn = ref(false);

// 排行榜数据
const leaderboard = ref([]);

// 获取排行榜数据
const fetchLeaderboard = async () => {
  try {
    const res = await getRunningLeaderboard({ limit: 5 });
    if (res.code === 0 && res.data) {
      leaderboard.value = res.data.map(item => ({
        id: item.studentId,
        name: item.studentName,
        avatar: item.avatar || 'https://randomuser.me/api/portraits/men/1.jpg',
        department: item.departmentName,
        distance: parseFloat(item.totalDistance.toFixed(1)),
        points: item.totalPoints
      }));
    }
  } catch (error) {
    console.error('获取排行榜数据失败', error);
    // 使用默认数据作为备份
    leaderboard.value = [
      {
        name: '李明',
        avatar: 'https://randomuser.me/api/portraits/men/2.jpg',
        department: '计算机学院',
        distance: 120.5,
        points: 1205
      },
      {
        name: '王芳',
        avatar: 'https://randomuser.me/api/portraits/women/3.jpg',
        department: '外国语学院',
        distance: 115.8,
        points: 1158
      },
      {
        name: '赵强',
        avatar: 'https://randomuser.me/api/portraits/men/4.jpg',
        department: '体育学院',
        distance: 110.2,
        points: 1102
      },
      {
        name: studentInfo.value.name,
        avatar: studentInfo.value.avatar,
        department: studentInfo.value.department,
        distance: 56.2,
        points: 280
      },
      {
        name: '刘华',
        avatar: 'https://randomuser.me/api/portraits/women/5.jpg',
        department: '医学院',
        distance: 45.6,
        points: 230
      }
    ];
  }
};

// 获取用户跑步统计数据
const fetchUserStats = async () => {
  try {
    const res = await getUserRunningStats({ userId: studentInfo.value.id });
    if (res.code === 0 && res.data) {
      runningData.value = {
        totalDays: res.data.totalDays || 0,
        totalDistance: parseFloat(res.data.totalDistance.toFixed(1)) || 0,
        points: res.data.totalPoints || 0
      };
    }
  } catch (error) {
    console.error('获取用户跑步统计数据失败', error);
  }
};

// 检查今日是否已打卡
const checkTodayStatus = async () => {
  try {
    const res = await checkTodayRunRecord({ userId: studentInfo.value.id });
    if (res.code === 0) {
      isCheckedIn.value = res.data;
    }
  } catch (error) {
    console.error('检查今日打卡状态失败', error);
  }
};

// 当前日期
const currentDate = computed(() => {
  const date = new Date();
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
});

// 打卡方法
const checkIn = async () => {
  if (!isCheckedIn.value) {
    try {
      // 模拟跑步数据
      const distance = Math.floor(Math.random() * 3) + 2; // 随机生成2-4公里
      const duration = distance * 400 + Math.floor(Math.random() * 200); // 配速约6-7分钟/公里
      const points = distance * 10;
      
      const now = new Date();
      const startTime = new Date(now.getTime() - duration * 1000);
      
      // 创建跑步记录
      const recordData = {
        studentId: parseInt(studentInfo.value.id),
        startTime: startTime.toISOString(),
        endTime: now.toISOString(),
        duration: duration,
        distance: distance,
        pace: `${Math.floor(duration/60/distance)}:${Math.floor((duration/60/distance % 1) * 60).toString().padStart(2, '0')}`,
        calorie: Math.floor(distance * 80),
        points: points,
        routeData: JSON.stringify({
          type: "LineString",
          coordinates: [[116.3912,39.9073],[116.3975,39.9088],[116.4020,39.9102]]
        }),
        status: 0,
        remark: '每日打卡'
      };
      
      const res = await createRunRecord(recordData);
      
      if (res.code === 0) {
        isCheckedIn.value = true;
        
        // 更新统计数据
        runningData.value.totalDays++;
        runningData.value.totalDistance += distance;
        runningData.value.points += points;
        
        // 重新获取排行榜数据
        await fetchLeaderboard();
        
        uni.showToast({
          title: '打卡成功',
          icon: 'success'
        });
      } else {
        uni.showToast({
          title: res.msg || '打卡失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('打卡失败', error);
      uni.showToast({
        title: '打卡失败，请重试',
        icon: 'none'
      });
    }
  }
};

// 页面加载时获取数据
onMounted(async () => {
  await Promise.all([
    fetchLeaderboard(),
    fetchUserStats(),
    checkTodayStatus()
  ]);
});
</script>

<!-- 样式已移至全局CSS文件 -->